<?php
/**
 * Created by PhpStorm.
 * User: W
 * Date: 2018/12/20
 * Time: 13:36
 */

namespace app\sports_admin\model;


use think\Model;
use think\db;
use think\Request;

//图书表
class DataBook extends Model
{
    protected $table = "data_book";
    protected $pk    = "id";
    //关联类型表
    public function getDataCategory()
    {
        return $this->belongsTo("DataCategory","catid","id")->field("id,catname");
    }
    //图书信息
    public static function content($id)
    {
        return self::with("getDataCategory")->where("id",$id['id'])->find();
    }
    public static function getBooks($page,$rows,$sort,$sortOrder,$searchName,$searchType)
    {
        $adminList = self::with('getDataCategory')
            ->where(function($query)use($searchName,$searchType){
                if($searchName){
                    $query->where('title','like',"%{$searchName}%");
                }elseif($searchType){
                    $query->where('catid','=',$searchType);
                }elseif ($searchType && $searchName){
                    $query->where('title','like',"%{$searchName}%")->where('catid','=',$searchType);
                }
            })
            ->page($page)
            ->limit($rows)
            ->order("{$sort}","{$sortOrder}")->select();

        $adminCount = self::with('getDataCategory')
            ->where(function($query)use($searchName,$searchType){
                if($searchName){
                    $query->where('title','like',"%{$searchName}%");
                }elseif($searchType){
                    $query->where('catid','=',$searchType);
                }elseif ($searchType && $searchName){
                    $query->where('title','like',"%{$searchName}%")->where('catid','=',$searchType);
                }
            })
            ->count();
        return ['rows'=>$adminList,'total'=>$adminCount];
    }

    //添加书籍信息
    public static function add()
    {
        $data = Request::instance()->only("catid,title,creator,publisher,date,pressyear,identifier,thumb,url");
        return self::insert(["catid"=>$data['catid'],
                "title"=>$data['title'],
                "creator"=>$data['creator'],
                "publisher"=>$data['publisher'],
                "date"=>$data['date'],
                "pressyear"=>$data['pressyear'],
                "identifier"=>$data['identifier'],
                "thumb"=>$data['thumb'],
                "url"=>$data['thumb']]);
    }
}